document.addEventListener('DOMContentLoaded', function () {
    const fieldMapping = {
        'field8413': '工作日期',
        'field8440': '项目名称',
        'field8411': '本日工作总结',
        'field8412': '明日工作计划',
        'field8410': '存在的问题和解决方案',
        'field8435': '工作地点'
    };

    // 从 Chrome 存储中加载上次填写的记录
    chrome.storage.local.get('formData', function (result) {
        const savedData = result.formData || {};

        // 创建字段输入框并填充已保存的数据
        const container = document.getElementById('dynamicFields');
        for (const [fieldId, fieldName] of Object.entries(fieldMapping)) {
            const div = document.createElement('div');
            div.className = 'field-item';
            div.innerHTML = `
        <label>${fieldName}</label>
        <input type="text" data-field="${fieldId}" value="${savedData[fieldId] || ''}">
      `;
            container.appendChild(div);
        }
    });

    // 添加日志区域
    const logArea = document.createElement('div');
    logArea.id = 'logArea';
    logArea.style.cssText = 'margin-top: 10px; padding: 5px; border: 1px solid #ddd; max-height: 100px; overflow-y: auto; font-size: 12px; color: #666;';
    document.body.appendChild(logArea);

    function log(message) {
        const logArea = document.getElementById('logArea');
        const time = new Date().toLocaleTimeString();
        logArea.innerHTML += `<div>[${time}] ${message}</div>`;
        logArea.scrollTop = logArea.scrollHeight;
        console.log(`[${time}] ${message}`); // 同时输出到控制台
    }

    document.getElementById('fillForm').addEventListener('click', function () {
        const values = {};
        const inputs = document.querySelectorAll('#dynamicFields input');
        inputs.forEach(input => {
            values[input.getAttribute('data-field')] = input.value;
        });

        // 保存填写的数据
        chrome.storage.local.set({ 'formData': values }, function () {
            log('数据已保存');
        });

        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            log('开始填充表单...');
            chrome.scripting.executeScript({
                target: { tabId: tabs[0].id },
                function: fillFormFields,
                args: [values]
            }, (results) => {
                if (chrome.runtime.lastError) {
                    log('错误: ' + chrome.runtime.lastError.message);
                } else {
                    log('表单填充完成');
                }
            });
        });
    });
});

// 填充表单的函数
function fillFormFields(values) {
    console.log('开始填充字段:', values);
    let filledCount = 0;

    for (const fieldId in values) {
        if (!values[fieldId]) continue;

        try {
            switch (fieldId) {
                case 'field8413': // 工作日期
                    const datePickerDiv = document.querySelector('.field8413_swapDiv .wea-date-picker');
                    if (datePickerDiv) {
                        // 直接设置显示文本
                        const textSpan = datePickerDiv.querySelector('.text');
                        if (textSpan) {
                            textSpan.textContent = values[fieldId];
                        }

                        // 设置隐藏输入框的值
                        const hiddenInput = document.getElementById(fieldId);
                        if (hiddenInput) {
                            hiddenInput.value = values[fieldId];
                            // 触发多个事件确保值被正确设置
                            hiddenInput.dispatchEvent(new Event('input', { bubbles: true }));
                            hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));

                            // 模拟日期选择完成的状态
                            const pickerSpan = datePickerDiv.querySelector('.ant-calendar-picker');
                            if (pickerSpan) {
                                pickerSpan.classList.add('ant-calendar-picker-selected');
                            }
                        }
                        filledCount++;
                    }
                    break;

                case 'field8440': // 项目名称
                    const projectInput = document.querySelector('.field8440_swapDiv .ant-select-search__field');
                    if (projectInput) {
                        projectInput.value = '';

                        projectInput.dispatchEvent(new Event('input', { bubbles: true }));
                        setTimeout(() => {
                            projectInput.value = values[fieldId];
                            projectInput.dispatchEvent(new Event('input', { bubbles: true }));
                            projectInput.dispatchEvent(new Event('change', { bubbles: true }));

                            // 第一步：获取项目列表
                            const currentTime = Date.now();
                            const randomTime = Date.now() + 1000;
                            const apiUrl = `https://oa.shenglong-info.com/api/public/browser/complete/161?q=${values[fieldId]}&type=browser.xmmc_all&fielddbtype=browser.xmmc_all&currenttime=${currentTime}&requestid=-1&workflowid=103&htgs_${currentTime}=0&wfid=103&billid=-93&isbill=1&f_weaver_belongto_userid=278&f_weaver_belongto_usertype=0&wfTestStr=&fieldid=8440&viewtype=0&fromModule=workflow&wfCreater=278&__random__=${randomTime}`;

                            fetch(apiUrl, {
                                headers: {
                                    'Accept': 'application/json'
                                },
                                credentials: 'include'
                            })
                                .then(response => response.json())
                                .then(data => {
                                    if (data && data.datas) {
                                        const projects = JSON.parse(data.datas);
                                        if (projects && projects.length > 0) {
                                            const project = projects[0];

                                            // 设置项目ID到隐藏输入框
                                            const hiddenInput = document.getElementById(fieldId);
                                            if (hiddenInput) {
                                                hiddenInput.value = project.id;
                                                hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
                                            }

                                            // 设置显示名称
                                            projectInput.value = project.name;
                                            projectInput.dispatchEvent(new Event('change', { bubbles: true }));

                                            // 第二步：调用确认接口
                                            const confirmParams = new URLSearchParams({
                                                requestid: '-1',
                                                workflowid: '103',
                                                nodeid: '619',
                                                formid: '-93',
                                                isbill: '1',
                                                triSource: '1',
                                                showAI: '0',
                                                triFieldid_256: '8440',
                                                rowIndexStr_256: '-1',
                                                triTableMark_256: 'main',
                                                field8440: project.id,
                                                linkageid: '256',
                                                wfTestStr: '',
                                                f_weaver_belongto_userid: '278',
                                                f_weaver_belongto_usertype: '0'
                                            });

                                            return fetch('https://oa.shenglong-info.com/api/workflow/linkage/reqDataInputResult', {
                                                method: 'POST',
                                                headers: {
                                                    'Content-Type': 'application/x-www-form-urlencoded',
                                                },
                                                body: confirmParams
                                            });
                                        }
                                    }
                                })
                                .then(response => response.json())
                                .then(data => {
                                    if (data && data.assignInfo_256 && data.assignInfo_256.changeValue) {
                                        // 设置项目编号
                                        const projectNoInput = document.getElementById('field8441');
                                        const projectNoSpan = document.getElementById('field8441span');
                                        if (projectNoInput && projectNoSpan) {
                                            const projectNo = data.assignInfo_256.changeValue.field8441.value;
                                            projectNoInput.value = projectNo;
                                            projectNoSpan.textContent = projectNo;
                                            projectNoInput.dispatchEvent(new Event('change', { bubbles: true }));
                                        }
                                    }
                                })
                                .catch(error => {
                                    console.error('项目名称填充错误:', error);
                                });
                        }, 100);
                        filledCount++;
                    }
                    break;

                case 'field8435': // 工作地点
                    const locationDiv = document.querySelector('.field8435_swapDiv');
                    if (locationDiv) {
                        // 先找到隐藏的输入框并设置值
                        const hiddenInput = document.getElementById('field8435');
                        if (hiddenInput) {
                            hiddenInput.value = values[fieldId];
                            hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
                        }

                        // 找到显示用的输入框并设置值
                        const visibleInput = locationDiv.querySelector('input.wf-input-field8435');
                        if (visibleInput) {
                            visibleInput.value = values[fieldId];
                            // 按顺序触发所有必要的事件
                            visibleInput.dispatchEvent(new Event('focus', { bubbles: true }));
                            visibleInput.dispatchEvent(new Event('input', { bubbles: true }));

                            // 延迟触发失焦事件，确保值被正确设置
                            setTimeout(() => {
                                visibleInput.dispatchEvent(new Event('blur', { bubbles: true }));
                                visibleInput.dispatchEvent(new Event('change', { bubbles: true }));

                                // 再次确保隐藏输入框的值被设置
                                if (hiddenInput) {
                                    hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
                                }
                            }, 100);
                        }
                        filledCount++;
                    } else {
                        console.warn('未找到工作地点输入框容器');
                    }
                    break;

                default:
                    const element = document.getElementById(fieldId);
                    if (element) {
                        element.value = values[fieldId];
                        element.dispatchEvent(new Event('change', { bubbles: true }));
                        filledCount++;
                    }
            }
            console.log(`成功填充字段 ${fieldId}`);
        } catch (e) {
            console.error(`填充字段 ${fieldId} 时出错:`, e);
        }
    }

    return `已填充 ${filledCount} 个字段`;
}

